package com.ruoyi.web.controller.zhudi;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.zhudi.domain.Graduation;
import com.zhudi.service.IGraduationService;
import com.zhudi.utils.ZhuDiUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

/**
 * 朱迪Controller
 * @author chongjin
 * @date 2021-02-17
 */
@Controller
@RequestMapping("/zhudi")
public class ZhuDiController extends BaseController {

    @Autowired
    private IGraduationService graduationService;

    @GetMapping("/excel")
    public String excel() {
        return "zhudi/excel_data";
    }

    /**
     * 导入数据
     */
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(@RequestParam("expertSubject") MultipartFile expertSubject,
                                 @RequestParam("originalData") MultipartFile originalData,
                                 @RequestParam("positiveNumber") String positiveNumber) throws Exception {
        if (expertSubject.isEmpty()) {
            return AjaxResult.error(ZhuDiUtil.EXPERT_FILE_EMPTY);
        }
        if (originalData.isEmpty()) {
            return AjaxResult.error(ZhuDiUtil.ORIGINAL_FILE_EMPTY);
        }
        if (StringUtils.isNotBlank(positiveNumber)) {
            ZhuDiUtil.POSITIVE = Integer.parseInt(positiveNumber);
        }
        Graduation graduation = graduationService.calWeight(expertSubject.getInputStream(),
                originalData.getInputStream());
        return graduationService.createResultFile(graduation);
    }

    /**
     * 下载数据
     */
    @GetMapping("/downloadData")
    public void downloadData(HttpServletResponse response) throws Exception {
        File file = new File(ZhuDiUtil.LOCAL_FILE_PATH + ZhuDiUtil.FILE_NAME);
        if (file.exists()) {
            response.setContentType("text/plain;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" +
                    java.net.URLEncoder.encode(ZhuDiUtil.FILE_NAME, "UTF-8"));
            byte[] buffer = new byte[1024];
            //文件输入流
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            //输出流
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer);
                i = bis.read(buffer);
            }
            bis.close();
        }
    }
}
